#!/bin/bash

# Create a WRT Widget
# Uses the yuicompressor library to compress the javascript and css files
#
# Usage: 
# 
# ./create-wrt-widget homedir widget
#
# where homedir is the widget code parent directory
# widget is the complete name of the widget, including path
#
# 2010 (c) Samuel kobelkowsky - yalla ya!
# samuel@yalla-ya.com

HOMEDIR=$1
TARGET=$2
TMPDIR=/tmp/`basename $TARGET.$$`

# Validate arguments
if [ -z "$HOMEDIR" -o -z "$TARGET" -o $# -ne 2 ]
then
  echo "Usage: $0 homedir widget"
  exit
fi

# Check that homedir exists
if [ ! -d $HOMEDIR ] 
then
  echo $HOMEDIR "doesn't exist"
  exit
fi

# Copy homedir to a temporary directory
mkdir -p $TMPDIR
cp -r $HOMEDIR/ $TMPDIR/`basename $TARGET .wgz`/

# Obfuscate and compress the code using yuicompressor
find $TMPDIR -type f -a \( -name '*.js' -o -name '*.css' \) -exec sh -c "/usr/bin/java -jar /usr/local/yuicompressor-2.4.2/build/yuicompressor-2.4.2.jar -o {}.mini {} ; mv {}.mini {}" \;

# Create the wgz file (filter the .svn files)
cd $TMPDIR
rm -f $TARGET
find . -path '*/.svn' -prune -o -type f -print | zip $TARGET -@ > /dev/null

# Clean the temp dir
cd /tmp
rm -rf $TMPDIR

echo 
echo "Built the JavaScript and CSS compressed $TARGET widget"
